package org.guiceside.commons.lang;


import java.lang.reflect.Array;

import javax.servlet.http.HttpServletRequest;



import org.apache.commons.lang.StringUtils;

/**
 * <p>
 * 将带有同一参数名称的参数值封装为数组进行返回
 * </p>
 * @author zhenjia <a href='mailto:zhenjiaWang@gmail.com'>email</a>
 * @since JDK1.5
 * @version 1.0 2008-9-7
 *
 **/
public class ArrayBuilder {
	@SuppressWarnings("unchecked")
	public  static <T> T[] buildModel(HttpServletRequest httpServletRequest, Class<?> T,String shortName)
	throws ArrayBuilderException {
		
		String[] parameterValues=httpServletRequest.getParameterValues(shortName);

		if(parameterValues==null){
			return null;
		}
		if(parameterValues.length==0){
			return null;
		}
		
		T[] results = (T[]) Array.newInstance(T, parameterValues.length);
		int index=0;
		for(String value:parameterValues){
			if(StringUtils.isBlank(value)){
				index++;
				continue;
			}
			results[index]=(T) BeanUtils.convertValue(value, T);
			index++;
		}
		return results;
	}
	
	public static Class<? extends Object> getArrayClass( Class<?> T){
		String tName=T.getName();
		int beginIndex=tName.indexOf("[L");
		int endIndex=tName.lastIndexOf(";");
		if(beginIndex>-1&&endIndex>-1){
			tName=tName.substring(beginIndex+2,endIndex);
		}
		try {
			Class<? extends Object> finalT=Class.forName(tName);
			return finalT;
		} catch (Exception e) {
			throw new ArrayBuilderException("not found class:"+tName, e);
		}
	}
}
